package tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-10-28
 * Time: 09:30
 */
//服务器
public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    /**
     * 构造函数
     * @param port 服务器要绑定的端口号
     * @throws IOException 创建Socket对象时可能会抛出此异常
     */
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动!");
        while (true){
            //因为TCP是有连接的，需要等待客户端的拨号，服务器来接收，通过accept方法接听电话，才能进行通信
            Socket clientSocket = serverSocket.accept(); //此时服务器阻塞，等待客户端拨号
            processConnection(clientSocket);
        }
    }
    //通过这个方法来处理一次连接，连接建立的过程就会涉及多次请求响应
    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线!\n",clientSocket.getInetAddress(),clientSocket.getPort());
        //循环读取客户端的请求
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            while (true){
                /*//通过inputStream读取客户端的请求
                byte[] requestBytes = new byte[1024];
                int readCount = inputStream.read(requestBytes);
                //因为read是把收到的数据放到byte数组中，但是我们需要转化字符串，所以使用另一种方式*/
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    System.out.printf("[%s:%d] 客户端下线!\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //1.读取请求并解析，要注意，next方法读取到空白符才会结束读取，所以需要要求客户端发来的请求中带有空白符，比如\n或空格
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.把响应写入到客户端,因为需要再返回的信息中添加\n，所以使用printWriter
                //outputStream.write(response.getBytes());
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();//刷新缓冲区，把数据写入到Socket中
                System.out.printf("[%s:%d] req: %s; resp: %s\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            clientSocket.close();
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();

    }
}
